package com.wngz.yudada.scoring;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wngz.yudada.manager.AiManager;
import com.wngz.yudada.model.dto.question.QuestionAnswerDTO;
import com.wngz.yudada.model.dto.question.QuestionContentDto;
import com.wngz.yudada.model.entity.App;
import com.wngz.yudada.model.entity.Question;
import com.wngz.yudada.model.entity.ScoringResult;
import com.wngz.yudada.model.entity.UserAnswer;
import com.wngz.yudada.model.vo.QuestionVO;
import com.wngz.yudada.service.QuestionService;
import com.wngz.yudada.service.ScoringResultService;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wngz.yudada.constant.AiQuestionConstant.AI_TEST_SCORING_SYSTEM_MESSAGE;

/**
 * AI测评类应用评分策略
 */
@ScoringStrategyConfig(appType = 1, scoringStrategy = 1)
@Slf4j
public class AiTestScoringStrategy implements ScoringStrategy {
    @Resource
    private QuestionService questionService;

    @Resource
    private AiManager aiManager;

    @Override
    public UserAnswer doScore(List<String> choices, App app) throws Exception {
        Long appId = app.getId();
        // 1. 根据 id 查询到题目
        Question question = questionService.getOne(
                Wrappers.lambdaQuery(Question.class).eq(Question::getAppId, appId)
        );
        QuestionVO questionVO = QuestionVO.objToVo(question);
        List<QuestionContentDto> questionContent = questionVO.getQuestionContent();

        // 2. 调用 AI 获取结果
        // 封装 Prompt
        String userMessage = getAiTestScoringUserMessage(app, questionContent, choices);
        // AI 生成
        String result = aiManager.doSyncStableRequest(AI_TEST_SCORING_SYSTEM_MESSAGE, userMessage);
        log.info("AI测评结果: {}", result);
        // 截取需要的 JSON 信息
        Map<String, Object> resultMap = JSONUtil.toBean(result, Map.class);
        String content = (String) resultMap.get("content");
        // 去掉 markdown 的 ```json
        String cleanJson = content
                .replace("```json", "")
                .replace("```", "")
                .trim();
        // 最终转为对象
        UserAnswer userAnswer = JSONUtil.toBean(cleanJson, UserAnswer.class);
        log.info("AI测评结果: {}", cleanJson);
        // 3. 构造返回值，填充答案对象的属性
        userAnswer.setAppId(appId);
        userAnswer.setAppType(app.getAppType());
        userAnswer.setScoringStrategy(app.getScoringStrategy());
        userAnswer.setChoices(JSONUtil.toJsonStr(choices));
        return userAnswer;
    }


    private String getAiTestScoringUserMessage(App app, List<QuestionContentDto> questionContentDTOList, List<String> choices) {
        StringBuilder userMessage = new StringBuilder();
        userMessage.append(app.getAppName()).append("\n");
        userMessage.append(app.getAppDesc()).append("\n");
        List<QuestionAnswerDTO> questionAnswerDTOList = new ArrayList<>();
        for (int i = 0; i < questionContentDTOList.size(); i++) {
            QuestionAnswerDTO questionAnswerDTO = new QuestionAnswerDTO();
            questionAnswerDTO.setTitle(questionContentDTOList.get(i).getTitle());
            questionAnswerDTO.setUserAnswer(choices.get(i));
            questionAnswerDTOList.add(questionAnswerDTO);
        }
        userMessage.append(JSONUtil.toJsonStr(questionAnswerDTOList));
        return userMessage.toString();
    }
}
